package xuanzhen.christian.service.impl;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import net.sf.json.JSONObject;
import xuanzhen.christian.dao.ChrisMapper;
import xuanzhen.christian.pojo.ChrisCus;
import xuanzhen.christian.service.ChrisService;
import xuanzhen.wx.pojo.AccessToken;
import xuanzhen.wx.pojo.WxUserMsg;
import xuanzhen.wx.util.WeixinUtil;
@Service
public class ChrisServiceImpl implements ChrisService {
	@Resource
	ChrisMapper chrisMapper;

	@Override
	public int insertCus(ChrisCus chrisCus) throws Exception {
		chrisMapper.insertCus(chrisCus);
		if(chrisMapper.queryListByCus(chrisCus)!=null){
			return 1;
		}
		return 0;
	}

	@Override
	public int updateCus(ChrisCus chrisCus) throws Exception {
		chrisMapper.addCusPhone(chrisCus);
		if(chrisMapper.queryListByCus(chrisCus)!=null){
			return 1;
		}
		return 0;
	}

	@Override
	public List<ChrisCus> queryListByCus(ChrisCus chrisCus) throws Exception {
		// TODO Auto-generated method stub
		return chrisMapper.queryListByCus(chrisCus);
	}

	@Override
	public List<ChrisCus> queryListByMap(Map<String, Object> parameter) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	/**
	 * 发送https请求获取用户信息
	 * @param at 网页授权获取的token对象
	 * @return 微信用户信息对象
	 * @throws UnsupportedEncodingException
	 */
	public ChrisCus catchUserMsg(AccessToken at) throws UnsupportedEncodingException{
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+at.getToken()+"&openid="+at.getOpenid()+"&lang=zh_CN";
		JSONObject json= WeixinUtil.httpRequest(url,"GET",null);
		ChrisCus us =new ChrisCus();
			us.setOpenid(json.getString("openid")); 
			us.setNickname(json.getString("nickname")); 
			us.setSex(json.getString("sex")); 
			us.setProvince(json.getString("province")); 
			us.setCity(json.getString("city")); 
			us.setCountry(json.getString("country"));    
			us.setHeadimgurl(json.getString("headimgurl")); 
			us.setPrivilege(json.getString("privilege")); 
		return us;
	}

}
